<script>
// 三方服务数据
import * as thirdQuery from '../../../utils/third-query.js';

export default {
  name: 'TripartiteRes',
  data() {
    return {
      columns: [], //数据列
      tableData: [], //数据
      dataType: '92400', //数据类型
      formItem: {
        dataTitle: '', //数据标题
        baseUrl: '', //服务地址
        type: 'GET', //请求类型
        searchUrl: '', //接口路径
        resType: 'form', //post请求参数类型
        params: [
          //接口参数
          {
            key: '',
            value: '',
          },
        ],
        pramJson: '', // post请求中的json参数
      },
      // 表单验证
      ruleValidate: {
        dataTitle: [{ required: true, message: '请输入数据表标题！', trigger: 'change' }],
        baseUrl: [{ required: true, message: '请输入服务地址！', trigger: 'change' }],
        searchUrl: [{ required: true, message: '请输入接口路径！', trigger: 'change' }],
      },
      showModal: false, // 显示查询结果的弹窗
      requestUrl: '', //请求地址
      spinShow: false, // 显示加载中
      sheetData: {}, //保存的三方数据
    };
  },
  computed: {
    setParamsType() {
      if (this.formItem.type === 'GET') {
        return true;
      } else if (this.formItem.type === 'POST' && this.formItem.resType === 'form') {
        return true;
      } else {
        return false;
      }
    },
  },
  methods: {
    // 新增参数
    addParams(index) {
      if (index === this.formItem.params.length - 1) {
        this.formItem.params.push({ key: '', value: '' });
      }
    },
    // 删除一行参数
    deleteParams(index) {
      this.formItem.params.splice(index, 1);
    },
    // 测试连接
    testConnection() {
      this.$refs['tripresform'].validate(valid => {
        if (valid) {
          // 验证成功
          this.spinShow = true;
          this.requestUrl = `${this.formItem.baseUrl}${this.formItem.searchUrl}`;
          this.sheetData = { requestUrl: this.requestUrl, type: this.formItem.type };
          const status = {
            POST() {
              this.sheetData.resType = this.formItem.resType;
              const resType = {
                async form() {
                  this.sheetData = {
                    params: this.formItem.params,
                    ...this.sheetData,
                  };
                  const response = await thirdQuery.post(
                    this.formItem.resType,
                    this.requestUrl,
                    this.formItem.params
                  );
                  this.showResData(response.data);
                },
                async json() {
                  this.sheetData = {
                    params: this.formItem.pramJson,
                    ...this.sheetData,
                  };
                  const response = await thirdQuery.post(
                    this.formItem.resType,
                    this.requestUrl,
                    this.formItem.pramJson
                  );
                  this.showResData(response.data);
                },
              };
              resType[this.formItem.resType].call(this);
            },
            async GET() {
              this.sheetData = {
                params: this.formItem.params,
                ...this.sheetData,
              };
              const response = await thirdQuery.get(this.requestUrl, this.formItem.params);
              this.showResData(response.data);
            },
          };
          status[this.formItem.type].call(this);
        } else {
          this.$Message.error('请按要求填写表单！');
        }
      });
    },
    //请求数据展示
    showResData(response) {
      this.showModal = true;
      const tableData = thirdQuery.setResData(response);
      this.setTableData(tableData);
    },
    // 表格数据处理
    setTableData(resData) {
      this.columns = [];
      if (resData.length !== 0) {
        for (let key in resData[0]) {
          this.columns.push({
            title: key,
            key: key,
            width: 180,
            maxWidth: 250,
            ellipsis: true,
          });
        }
      }
      this.tableData = resData;
      this.spinShow = false;
    },
    // 重置
    reset() {
      this.$refs['tripresform'].resetFields();
      this.formItem.params = [
        {
          key: '',
          value: '',
        },
      ];
      this.formItem.pramJson = '';
    },
    //获取新增数据
    getAddedModel() {
      let newData = {
        name: this.formItem.dataTitle,
        dataType: this.dataType,
        data: { ...this.sheetData },
        createTime: new Date(),
      };
      return newData;
    },
    // 数据校验
    validateData() {
      let isValid;
      this.$refs['tripresform'].validate(valid => {
        if (valid) {
          isValid = true;
          return;
        } else {
          isValid = false;
          this.$Message.error('请按要求填写表单！');
          return;
        }
      });
      return isValid;
    },
  },
};
</script>

<template>
  <div class="datav-trip-res">
    <h2>三方服务数据</h2>
    <Spin
      v-if="spinShow"
      fix>
      <loading type="ball-grid-pulse" />
    </Spin>
    <Row>
      <Form
        ref="tripresform"
        :rules="ruleValidate"
        :model="formItem"
        :label-width="90"
        label-position="right">
        <FormItem
          prop="dataTitle"
          label="数据标题：">
          <Input
            v-model="formItem.dataTitle"
            placeholder="输入数据标题"
          ></Input>
        </FormItem>
        <FormItem
          prop="baseUrl"
          label="服务地址：">
          <Input
            v-model="formItem.baseUrl"
            placeholder="eg：http://192.168.1.151:8080"
          ></Input>
        </FormItem>
        <FormItem
          prop="searchUrl"
          class="form-searchurl"
          label="接口路径：">
          <Select
            v-model="formItem.type"
            style="width:70px"
          >
            <Option value="GET">GET</Option>
            <Option value="POST">POST</Option>
          </Select>
          <Input
            v-model="formItem.searchUrl"
            placeholder="eg：/resource/catalog/delete"
          ></Input>
        </FormItem>
        <FormItem
          label="接口参数：">
          <RadioGroup
            v-if="formItem.type === 'POST'"
            v-model="formItem.resType">
            <Radio label="form">form</Radio>
            <Radio label="json">json</Radio>
          </RadioGroup>
          <div
            v-if="setParamsType"
            class="form-cont">
            <div
              v-for="(item,index) in formItem.params"
              :key="index"
              class="form-params">
              <Input
                v-model="item.key"
                placeholder="参数名称"
                @on-change="addParams(index)"
              ></Input>
              <Input
                v-model="item.value"
                placeholder="参数值"
              ></Input>
              <Icon
                v-if="formItem.params.length!==1"
                :size="20"
                type="ios-close-outline"
                title="删除该行参数"
                @click.native.stop="deleteParams(index)" />
            </div>
          </div>
          <Input
            v-else
            v-model="formItem.pramJson"
            :rows="4"
            type="textarea"
            placeholder="请输入您要请求的参数..."></Input>
        </FormItem>
        <FormItem>
          <Button
            type="info"
            @click="testConnection">测试连接</Button>
          <Button
            type="ghost"
            @click="reset">重置</Button>
        </FormItem>
      </Form>
    </Row>
    <Modal
      v-model="showModal"
      width="600px"
      height="400px">
      <p slot="header">
        查看数据
      </p>
      <Table
        :columns="columns"
        :data="tableData"
        height="380"
        width="500px"
        border>
      </Table>
    </Modal>
  </div>
</template>

<style lang="less" scoped>
.datav-trip-res {
  .k-row {
    margin-top: 10px;
  }

  .k-input-wrapper {
    width: 95%;
  }
  .text-preview {
    width: 100%;
  }

  .k-form {
    width: 90%;
    margin: 0 auto;

    .k-form-item {
      margin-bottom: 20px;
    }

    .form-searchurl {
      /deep/.k-input-wrapper {
        width: 75%;
      }
    }
    /deep/.form-cont {
      max-height: 120px;
      overflow-y: auto;
    }
    /deep/.form-params {
      margin-bottom: 8px;
      /deep/.k-input-wrapper {
        margin-right: 5px;
        width: 55%;
        float: left;
      }
      /deep/.k-input-wrapper:first-child {
        width: 30%;
      }
      /deep/.k-input-wrapper:last-child {
        margin-right: 10px;
      }
    }
  }
}
</style>
